package com.example.administrator.xxnapp.http;

import android.app.Dialog;
import android.util.Log;

import com.example.administrator.xxnapp.util.des3.Des3;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Went_Gone on 2017/10/17.
 */

public abstract class ResultStringCallback extends StringCallback {
    private Dialog dialog;

    public ResultStringCallback() {
    }

    @Override
    public void onError(Response<String> response) {
        super.onError(response);
        onResultOther(ResultCode.ERROR,"请稍后重试");
    }

    public ResultStringCallback(Dialog dialog) {
        this.dialog = dialog;
    }

    @Override
    public void onSuccess(Response<String> response) {
        Gson gson = new Gson();
        try {
            JSONObject object = new JSONObject(response.body());
            if (object.isNull("result")){
                onSuccessString(gson,response.body());
            }else {
                if (object.getInt("result") == 200){
                    String data = "";
                    if (!object.isNull("data")){
                        data = object.getString("data");
                    }else {
                        Log.e("TAG", "onSuccess: ");
                        data = "";
                    }
                    onResultSuccess(gson,data);
                }else {
                    onResultOther(object.getInt("result"),object.getString("message"));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onSuccessString(Gson gson,String responseBody){

    }

    @Override
    public void onFinish() {
        super.onFinish();
        if (dialog!=null && dialog.isShowing()){
            dialog.dismiss();
        }
    }

    public abstract void onResultSuccess(Gson gson,String dataJsonStr);
    public abstract void onResultOther(int result,String message);

    public interface ResultCode{
        int SUCCESS = 200;
        int ERROR = -1;
    }
}
